#pragma once
#include "common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
const static int backlog = 8;

// 服务器往往是禁止拷贝的
using namespace LogMoudle;
using namespace ThreadPoolMoudle;
class TcpServer : public Nocopy
{
public:
    TcpServer(uint16_t port)
        : _port(port), _listensockfd(-1), _isrunning(false)
    {
    }
    void init()
    {
        // 1. 创建套接字文件
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(loglevel::FATAL) << "socket error";
            exit(SOCKET_ERR);
        }
        LOG(loglevel::INFO) << "socket success: " << _listensockfd; // 3
        // 2. bind众所周知的端口号
        InetAddr local(_port);
        int n = bind(_listensockfd, local.NetAddrPtr(), local.NetAddrLen());
        if (n < 0)
        {
            LOG(loglevel::FATAL) << "bind error";
            exit(BIND_ERR);
        }
        LOG(loglevel::INFO) << "bind success: " << _listensockfd; // 3
        // 3. 设置socket状态为listen
        n = listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(loglevel::FATAL) << "listen error";
            exit(LISTEN_ERR);
        }
        LOG(loglevel::INFO) << "listen success: " << _listensockfd; // 3
    }
    class ThreadData
    {
    public:
        ThreadData(int fd, InetAddr &ar, TcpServer *s) : sockfd(fd), addr(ar), tsvr(s)
        {
        }

    public:
        int sockfd;
        InetAddr addr;
        TcpServer *tsvr;
    };
    void Service(int sockfd, InetAddr &as)
    {
        char buffer[1024];
        while (true)
        {
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(loglevel::DEBUG) << as.StringAddr() << " #" << buffer;
                std::string echo_string = "echo# ";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                LOG(loglevel::DEBUG) << as.StringAddr() << " 退出了...";
                close(sockfd);
                break;
            }
            else
            {
                LOG(loglevel::DEBUG) << as.StringAddr() << " 异常...";
                close(sockfd);
                break;
            }
        }
    }
    static void* Routine(void* td)//线程执行函数
    {
        pthread_detach(pthread_self());//线程分离状态
        ThreadData* d=static_cast<ThreadData*> (td);
        d->tsvr->Service(d->sockfd,d->addr);
        delete d;
        return nullptr;
    }
    void run()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 获取连接
            struct sockaddr_in as;
            socklen_t n = sizeof(sockaddr_in);
            int sockfd = accept(_listensockfd, CONV(as), &n);
            if (sockfd < 0)
            {
                LOG(loglevel::WARNING) << "accept error";
                continue;
            }
            InetAddr addr(as);
            LOG(loglevel::INFO) << "accept success, peer addr : " << addr.StringAddr();
            // Service(sockfd, addr); // 单进程程序
            //  多进程banben
            // pid_t id = fork();
            // if (id < 0)
            // {
            //     LOG(loglevel::FATAL) << "fork error";
            //     exit(FORK_ERR);
            // }
            // else if (id == 0)
            // {
            //     close(_listensockfd);
            //     if (fork() > 0) // 再次fork，子进程退出
            //         exit(OK);

            //     Service(sockfd, addr); // 孙子进程，孤儿进程，系统回收
            //     exit(OK);
            // }
            // else
            // {
            //     close(sockfd);
            //     pid_t rid = waitpid(id, nullptr, 0);
            //     (void)rid;
            // }
            // version2: 多线程版本
            ThreadData *td = new ThreadData(sockfd, addr, this);
            pthread_t tid;
            pthread_create(&tid, nullptr, Routine, td);
            //线程池版本
            //将新链接和客户端构建一个新的任务，push线程池中
            // ThreadPool<task_t>::GetInstance()->Enqueue([this, sockfd, &addr](){
            //     this->Service(sockfd, addr);
            // });
            
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
};